package com.ahstu.learning.learning;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ahstu.learning.R;
import com.ahstu.learning.SubjectActivity.CourseAdapter;
import com.ahstu.learning.bean.CourseMessage;
import com.ahstu.learning.SubjectActivity.Subject;
import com.ahstu.learning.player.VodActivity;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

public class LearningFragement extends Fragment implements OnPageChangeListener,
        OnClickListener {
    // 设置广告栏中的fragment数量为10000，达到循环效果
    private final int ADSum = Integer.MAX_VALUE;
    private int[] imgIds = new int[]{R.id.bannerimg1, R.id.bannerimg2,
            R.id.bannerimg3};                        //滚动栏imageview
    private int[] bannerIds = new int[]{R.drawable.banner01,
            R.drawable.banner02, R.drawable.banner03};                                        //滚动栏图片
    private View view;
    private ViewPager viewPager;
    private PageFragment fragment;

    private TextView first_title;
    private EditText search_course_et;
    private boolean search_state;
//    private RelativeLayout scroll_layout;
//    private LinearLayout learning_course_layout;

    private RelativeLayout learning_main_fragment_layout;
    private LinearLayout course_search_progress_layout;
    private ProgressBar course_search_progress;
    private TextView course_search_result;
    private ListView search_course_listview;
    private ArrayList<Subject> sublist;
    private ImageView search_course_iv;

    // 判断是否为手动滑动片段,默认为自动,即false
    private boolean isScolling = false;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            final String course_name=search_course_et.getText().toString().trim();
            if(search_state==false){
                first_title.setVisibility(View.GONE);
                search_course_et.setVisibility(View.VISIBLE);
                search_state=true;
            }else if(course_name.isEmpty()){
                first_title.setVisibility(View.VISIBLE);
                search_course_et.setVisibility(View.GONE);
                search_course_iv.setImageResource(R.drawable.course_search);
//                learning_main_fragment_layout.setVisibility(View.VISIBLE);
                search_course_listview.setVisibility(View.GONE);
                course_search_progress_layout.setVisibility(View.GONE);
                search_state=false;
            }else{
//                search_course_iv.setImageResource(R.drawable.course_search_clear);
//                learning_main_fragment_layout.setVisibility(View.GONE);
                course_search_progress_layout.setVisibility(View.VISIBLE);
                course_search_progress.setVisibility(View.VISIBLE);
                course_search_result.setText("正在查找相关课程...");

                BmobQuery<CourseMessage> query=new BmobQuery<>();
//                query.addWhereContains("coursename","地理");
//                query.addWhereEqualTo("coursename","揭秘地理大纲试题");
                query.findObjects(getActivity(), new FindListener<CourseMessage>(){
                    @Override
                    public void onSuccess(List<CourseMessage> list) {
                        course_search_progress_layout.setVisibility(View.GONE);
                        search_course_listview.setVisibility(View.VISIBLE);
                        sublist=new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            if(list.get(i).getCoursename().contains(course_name)){
                                Subject subject = new Subject();
                                subject.setCoursename(list.get(i).getCoursename());
                                subject.setImageurl(list.get(i).getImage());
                                subject.setPlayId(list.get(i).getPlayId());
                                subject.setPlayUrl(list.get(i).getPlayUrl());
                                subject.setCourseinfo(list.get(i).getCourseinfo());
                                subject.setObjectid(list.get(i).getObjectId());
                                subject.setCommemt(list.get(i).getComment());
                                subject.setVedioId(list.get(i).getVedioId());
                                subject.setCourseType(list.get(i).getCourseType());
                                sublist.add(subject);
                            }
//                            Log.i("learningfrg96 "+i,list.get(i).toString());
                        }
                        if(sublist.size()==0){
                            course_search_progress_layout.setVisibility(View.VISIBLE);
                            course_search_progress.setVisibility(View.GONE);
                            search_course_listview.setVisibility(View.GONE);
                            course_search_result.setText("未找到相关课程，换个课程名试试~");
                        }else{
                            search_course_listview.setVisibility(View.VISIBLE);
                            search_course_listview.setAdapter(new CourseAdapter(sublist,getActivity()));
                        }

                    }

                    @Override
                    public void onError(int i, String s) {
                        course_search_progress.setVisibility(View.GONE);
                        course_search_result.setText("未找到相关课程，换个课程名试试~");
                        Toast.makeText(getActivity(),"error",Toast.LENGTH_SHORT).show();
                    }
                });


            }
            search_course_et.setText("");

        }
    };
    private Runnable myrunnable = new Runnable() {
        public void run() {
            if (!isScolling) {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            }
            handler.postDelayed(this, 3000);                                                    //间隔3秒
        }
    };



//    private ArrayList<String> arrayList = new ArrayList<String>();
//    private Object[] course_name;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.base_learning, null);
        viewPager = (ViewPager) view.findViewById(R.id.viewPager1);
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        viewPager.addOnPageChangeListener(this);
        // 设置广告栏的初始化位置在中间，即左右都可以滑动
        viewPager.setCurrentItem(ADSum / 3);
        refresh();

        initView();

        return view;
    }

    private void initView() {
        course_search_progress_layout= (LinearLayout) view.findViewById(R.id.course_search_progress_layout);
        course_search_progress= (ProgressBar) view.findViewById(R.id.course_search_progress);
        course_search_result= (TextView) view.findViewById(R.id.course_search_result_tv);

        //课程选项按钮
        view.findViewById(R.id.subject1).setOnClickListener(this);
        view.findViewById(R.id.subject2).setOnClickListener(this);
        view.findViewById(R.id.subject3).setOnClickListener(this);
        view.findViewById(R.id.subject4).setOnClickListener(this);
        view.findViewById(R.id.subject5).setOnClickListener(this);
        view.findViewById(R.id.subject6).setOnClickListener(this);
        view.findViewById(R.id.subject7).setOnClickListener(this);
        view.findViewById(R.id.subject8).setOnClickListener(this);
        view.findViewById(R.id.subject9).setOnClickListener(this);
        search_course_iv= (ImageView) view.findViewById(R.id.search_course_iv);
        first_title= (TextView) view.findViewById(R.id.first_page);

        search_course_et= (EditText) view.findViewById(R.id.search_course_et);
        search_course_et.setSingleLine();
        learning_main_fragment_layout= (RelativeLayout) view.findViewById(R.id.learning_main_fragment_layout);
        search_course_listview= (ListView) view.findViewById(R.id.search_course_listview);
//        search_course_listview.setOnItemClickListener((AdapterView.OnItemClickListener) getActivity());

        search_course_iv.setOnClickListener(this);
        search_course_et.addTextChangedListener(textWatcher);
        search_course_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int j, long l) {

                Intent intent=new Intent(getActivity(), VodActivity.class);
                intent.putExtra("objectid", sublist.get(j).getObjectid());
                intent.putExtra("playId", sublist.get(j).getPlayId());
                intent.putExtra("playUrl", sublist.get(j).getPlayUrl());
                intent.putExtra("course_name", sublist.get(j).getCoursename());
                intent.putExtra("course_info", sublist.get(j).getCourseinfo());
                Subject subject = new Subject();
                subject.setCourse_commemt_list(sublist.get(j).getCommemt());
                subject.setCourse_title(sublist.get(j).getCoursename());
                startActivity(intent);
            }
        });
    }

    private TextWatcher textWatcher=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if(charSequence.toString().isEmpty()&&(search_course_et.getVisibility()==View.VISIBLE)){
                search_course_iv.setImageResource(R.drawable.course_search_clear);
            }else
                search_course_iv.setImageResource(R.drawable.course_search);
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                isScolling = false;
                break;
            case ViewPager.SCROLL_STATE_DRAGGING:
                isScolling = true;
                break;
        }
    }

    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    public void onPageSelected(int arg0) {
        for (int i = 0; i < imgIds.length; i++) {
            ImageView imageView = (ImageView) view.findViewById(imgIds[i]);
            if (arg0 % 3 == i) {
                imageView.setBackgroundResource(R.drawable.trend_dot_night);
            } else {
                imageView.setBackgroundResource(R.drawable.trend_dot_day);
            }
        }
    }

    public void refresh() {
        handler.postDelayed(myrunnable, 2000);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.subject1:
                openActivity(Course_list.class,"Chinese");
                break;
            case R.id.subject2:
                openActivity(Course_list.class,"Math");
                break;
            case R.id.subject3:
                openActivity(Course_list.class,"English");
                break;
            case R.id.subject4:
                openActivity(Course_list.class,"Physical");
                break;
            case R.id.subject5:
                openActivity(Course_list.class,"Chymist");
                break;
            case R.id.subject6:
                openActivity(Course_list.class,"Biology");
                break;
            case R.id.subject7:
                openActivity(Course_list.class,"Politics");
                break;
            case R.id.subject8:
                openActivity(Course_list.class,"History");
                break;
            case R.id.subject9:
                openActivity(Course_list.class,"Geography");
                break;
            case R.id.search_course_iv:
                Message message=new Message();
                handler.sendMessage(message);

                InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
            default:
                break;
        }
    }

    //Activity跳转
    private void openActivity(Class tuen_class,String subject){
        Intent intent = new Intent(getActivity(), tuen_class);
        intent.putExtra("subject",subject);
        startActivity(intent);
        this.getActivity().overridePendingTransition(R.anim.enteranim,0);
    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        public Fragment getItem(int arg0) {
            fragment = new PageFragment();
            fragment.setPagePicture(bannerIds[arg0 % 3]);
            return fragment;
        }
        public int getCount() {
            return ADSum;
        }
    }

}
